#pragma once 
#include <iostream>
#include <unistd.h>
#include <vector>
using namespace std;
// 进程任务

typedef void(*work_t)(int); // 定义一个函数指针, 传入一个管道读端fd
typedef void(*task_t)(int, pid_t); // 定义一个函数指针

// 一些任务
void PrintLog(int rfd, pid_t id)
{
    cout << "Task instruction is read from " << rfd << " and PrintLog task is completed by " << id << endl;
}

void ReloadConf(int rfd, pid_t id)
{
    cout << "Task instruction is read from " << rfd << " and ReloadConf task is completed by " << id << endl;
}


void ConnectMysql(int rfd, pid_t id)
{
    cout << "Task instruction is read from " << rfd << " and ConnectMysql task is completed by " << id << endl;
}

vector<task_t> tasks = { PrintLog,  ReloadConf, ConnectMysql };

// 随机生成一个任务下标
uint32_t NextTask()
{
    return rand() % tasks.size();
}


//  从键盘读取下标指定进程完成哪个任务
void worker(int rfd)
{
    while(true)
    {
        uint32_t command_code = 0;
        ssize_t n = read(0, &command_code, sizeof(command_code));
        if(n == sizeof(command_code))
        {
            if(command_code >= tasks.size()) continue;
            // 根据读取到的下标，调用对应的函数
            tasks[command_code](rfd, getpid());
        }
        else if(n == 0) // 当子进程从管道读取的字节数等于0时，就退出任务
        {
            cout << "Process of " << getpid() << " is exited !!!" << endl;
            break;
        }
    }
}

